const { HttpException } = require('../core/http-exception')

const catchError = async (ctx, next) => {
    try {
        await next()
    } catch (error) {

        const isDev = global.config.environment === 'env'
        const isHttpException = error instanceof HttpException

        if (isDev && !isHttpException) {
          throw error
        }

        if (error instanceof HttpException) {
            ctx.body = {
                validatorMsg: typeof error.msg === 'string' ? [error.msg] : error.msg,
                msg: typeof error.msg === 'string' ? error.msg : error.msg[0],
                data: error.data || '',
                errorCode: error.errorCode,
                method: `${ctx.method}`,
                path: `${ctx.path}`
            }
        } else {
            ctx.body = {
                validatorMsg: [],
                msg: '请求出错',
                data: error.data || '',
                errorCode: 404,
                method: `${ctx.method}`,
                path: `${ctx.path}`
            }
        }
    }
}

module.exports = catchError
